package cn.com.pxto.web.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class DateTimePicker extends BodyTagSupport {
	private String elementid;
	private String name;
	private boolean canNull = true;
	private String format = "%Y-%m-%d";
	private boolean showTime = false;
	private String styleClass = null;
	private String style = null;
	private String value=null;
	public void setCanNull(boolean canNull) {
		this.canNull = canNull;
	}

	public void setFormat(String format) {
		this.format = format;
	}

	public void setElementid(String elementid) {
		this.elementid = elementid;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setShowTime(boolean showTime) {
		this.showTime = showTime;
	}
	
	public void setStyle(String style) {
		this.style = style;
	}

	public void setStyleClass(String styleClass) {
		this.styleClass = styleClass;
	}
	public void setValue(String value) {
		if(value == null || value.equals("0")){
			value = "";
		}
		this.value = value;
	}

	public int doStartTag() throws JspException {
		try{
			JspWriter out = pageContext.getOut();
			StringBuffer textBox = new StringBuffer("<input name=\""+name+"\" id=\""+elementid+"\" readonly type=\"text\" value=\""+value+"\"");
			if (style!=null) textBox.append(" style=\""+styleClass+"\"");
			if (styleClass!=null) textBox.append(" class=\""+styleClass+"\"");
			textBox.append("/>\n");
			out.print(textBox.toString());
			out.print("<script type=\"text/javascript\">\n");
			if (!canNull){
				out.print("document.getElementById(\""+elementid+"\").validateResult = false;\n");
			}
			out.print("Calendar.setup({\n");
			out.print("		inputField     :    \""+elementid+"\",\n");// id of the input field
			out.print("		ifFormat       :    \""+format+"\",\n");// format of the input field "%Y-%m-%d %H:%M:%S"
			out.print("		showsTime      :    "+showTime+",\n");// trigger for the calendar (button ID)
			out.print("		button         :    \""+elementid+"\",\n");//show all years in drop-down boxes (instead of every other year as default)
			out.print("		step           :    1\n");
			if (!canNull){
				out.print("		,onUpdate       :    function(){document.getElementById(\""+elementid+"\").validateResult = true;}\n");
			}
			out.print("})\n");
			out.print("</script>\n");
		}catch(IOException e){
			throw new JspException("Print Error:" + 
                    e.getMessage());
		}
		return super.doStartTag();
	}
}
